package com.zxy.fmmall.controller;


import com.github.wxpay.sdk.WXPay;
import com.zxy.fmmall.entity.Orders;
import com.zxy.fmmall.service.OrdersService;
import com.zxy.fmmall.service.job.MyPayConfig;
import com.zxy.fmmall.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("orders")
@CrossOrigin
@Api(value = "提供订单详情接口", tags = "订单管理")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @ApiOperation("添加订单")
    @PostMapping("/add")
    public ResultVo addOrders(String cids, @RequestBody Orders orders) {
        ResultVo ok = ResultVo.ok();
        try {
            Map<String, String> orderInfo = ordersService.addOrders(orders, cids);
            WXPay wxPay = new WXPay(new MyPayConfig());
            HashMap<String, String> map = new HashMap<>();
            map.put("body", orderInfo.get("productNames"));             //  商品描述
            map.put("trade_type", "CNY");              // 支付币种
            map.put("out_trade_no", orderInfo.get("orderId")); //使用当前用户订单的编号作为当前支付交易的交易号
            map.put("total_fee","1");               //支付金额   orders.getActualAmount()*100+""
            map.put("trade_type", "NATIVE");         //交易类型
            map.put("notify_url","https://3ad6-120-216-179-100.jp.ngrok.io/pay/callback");   //设置支付完成时返回的地址
            Map<String, String> res = wxPay.unifiedOrder(map);
            ok.data("payUrl",res.get("code_url")).data("productNames",orderInfo.get("productNames")).data("orderId",orderInfo.get("orderId"));
        } catch (SQLException e) {
            return ResultVo.error().message("提交订单失败");
        } catch (Exception e) {
            return ResultVo.error().message("库存不足或提交订单失败");
        }
        return ok;
    }


    @ApiOperation("查询商品支付状态")
    @GetMapping("/orderStatus/{oid}")
    public ResultVo getOrderStatus(@PathVariable("oid") String orderId){
        return ordersService.getOrderById(orderId);
    }

    @ApiOperation("根据用户id查询订单")
    @GetMapping("/getOrderByUserId/{userId}")
    public ResultVo getOrderByUserId(@PathVariable("userId")String userId, String status, int pageNum, int limit){
        return ordersService.getOrderByUserId(userId,status,pageNum,limit);
    }


}
